package ch.zhaw.skuh.turing.controller;

import java.util.HashSet;

public final class Factory {

	public static final String DELIMITER = " ";
	public static final char BLANK = '_';
	public static final int OFFSET = 15;

	public static boolean validateNumber(String n) {
		try {
			return Long.parseLong(n) > 0;
		} catch (NumberFormatException nfe) {
			return false;
		}
	}

	public static boolean validateNumberList(String input, String delim) {
		return validateNumberList(input, delim, 0);
	}

	public static boolean validateNumberList(String input, String delim,
			int maxlength) {
		String[] list = input.split(delim);
		if (maxlength > 0 && list.length > maxlength) {
			return false;
		}
		for (String element : list) {
			if (!validateNumber(element)) {
				return false;
			}
		}
		return true;
	}

	public static long[] toNumber(String input, String delim) {
		String[] list = input.split(delim);
		long[] result = new long[list.length];
		for (int i = 0; i < list.length; i++) {
			if (validateNumber(list[i])) {
				result[i] = Long.parseLong(list[i]);
			}
		}
		return result;
	}

	public static char toChar(int i) {
		if (i >= 0 && i <= 9) {
			return Character.forDigit(i, 10);

		}
		throw new IndexOutOfBoundsException();
	}

	public static final char[] valueOf(int length, char c) {
		char[] result = new char[length];
		for (int i = 0; i < length; i++) {
			result[i] = c;
		}
		return result;
	}

	public static final int count(String text, Character ch) {
		/*
		 * stack overflow with following code ... int pos = text.indexOf(ch);
		 * return pos == -1 ? 0 : 1 + count(text.substring(pos + 1), ch);
		 */
		// silly loop
		int result = 0;
		for (int i = 0; i < text.length(); i++) {
			if (text.charAt(i) == ch) {
				result++;
			}
		}
		return result;
	}

	public static final StringBuilder concatInt(int[] input, char digit,
			char nonDigit) {
		int length = input.length - 1;
		for (int i = 0; i < input.length; i++) {
			length += input[i];
		}
		StringBuilder result = new StringBuilder(length);

		for (int i = 0; i < input.length; i++) {
			for (int j = 0; j < input[i]; j++) {
				result.append(digit);
			}
			if (i < input.length - 1) {
				result.append(nonDigit);
			}
		}
		return result;
	}

	public static boolean allUnique(String s) {
		HashSet<Character> hs = new HashSet<Character>(s.length()); // This can
																	// be tuned,
																	// obviously
		for (int i = 0; i < s.length(); i++) {
			if (!hs.add(s.charAt(i))) {
				return false;
			}
		}
		return true;
	}
}
